package com.tpl.core.basedata.common.task;

import com.tpl.core.basedata.service.sys.TriggerTaskService;
import com.tpl.core.common.Global;
import com.tpl.core.common.task.TriggerTaskSupport;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


/**
 * 定时任务执行类
 *
 */
public class TriggerTaskExecute {
	private Log log= LogFactory.getLog(TriggerTaskExecute.class);
	TriggerTaskService triggerTaskService=(TriggerTaskService) Global.getContext().getBean("triggerTaskService");
	/**
	 * 执行定时任务
	 * @param id
	 * @param sourceId
	 * @param sourceService 源执行类,必须实现TreggerTaskSurce接口
	 */
	public void execute(Long id,String sourceId,String sourceService){
		TriggerTaskSupport source=null;
		try {
			source=(TriggerTaskSupport)Global.getContext().getBean(sourceService);
		} catch (Exception e) {
		}
		if(source==null){
			try {
				source=(TriggerTaskSupport) Class.forName(sourceService).newInstance();
			} catch (Exception e) {
				log.error("create task source["+sourceService+"] error:"+e.getMessage());
			}
			if(source==null){
				log.error("source["+sourceService+"] cannot find");
				return;
			}
		}
		try {
			source.executeTask(sourceId);
			writeLog(id, 0,"success");
		} catch (Exception e) {
			writeLog(id, -1,e.getMessage());
			log.error("执行定时任务失败.source:"+sourceService+";sourceId:"+sourceId+";error:"+e.getMessage());
		}
	}
	private void writeLog(Long id,int state,String info){
		triggerTaskService.doWriteLog(id, state, info);
    	log.info("job excute end");
	}
}
